﻿using CDV.IRMS.Model;
using CDV.IRMS.WebAPI.TaskExecution.Data;
using CDV.IRMS.WebAPI.TaskExecution.Utils;
using log4net;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace CDV.IRMS.WebAPI.TaskExecution.Interface.Impl
{
    /// <summary>
    /// 任务路由数据交互实现类
    /// </summary>
    public class TaskManagerServiceImpl : ITaskManagerService
    {
        /// <summary>
        /// Log对象
        /// </summary>
        private readonly ILog _logger = ServiceInjector.ServiceProvider.GetService<ILog>();

        /// <summary>
        /// 任务管理RESTfulAPI
        /// </summary>
        public RESTfulAPI RESTfulAPI { get; set; }

        /// <summary>
        /// 查询任务路由数据
        /// </summary>
        /// <param name="beginTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="routeStatus">路由线路状态</param>
        /// <returns>任务路由列表</returns>
        public (IList<TaskRouteInfoModel>, string) QueryTask(DateTime beginTime, DateTime endTime, int? routeStatus)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(RESTfulAPI.BaseURL);
                httpClient.Timeout = RESTfulAPI.TimeOut;

                var requestUri = string.Format(RESTfulAPI.APIMap["QueryTask"], beginTime, endTime, routeStatus);

                var response = httpClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead);
                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResult = response.Result.Content.ReadAsStringAsync().Result;

                    var result = JsonConvert.DeserializeAnonymousType(jsonResult,
                        new { isOK = false, msg = "", Data = new List<TaskRouteInfoModel>() });

                    _logger.Debug($"RequestUri: {requestUri}, Result: [IsOK={result.isOK}, Msg={result.msg}]");

                    return (result.Data, result.msg);
                }
                return (null, $"任务路由数据获取失败[StatusCode:{response.Result.StatusCode}]");
            }
        }

        /// <summary>
        /// 更新任务路由状态
        /// </summary>
        /// <param name="taskID">任务ID</param>
        /// <param name="routeID">路由ID</param>
        /// <param name="routeStatus">路由线路状态</param>
        /// <returns>true：更新成功</returns>
        public (bool, string) UpdateRouteStatus(int taskID, int routeID, ERouteStatus routeStatus)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.BaseAddress = new Uri(RESTfulAPI.BaseURL);
                httpClient.Timeout = RESTfulAPI.TimeOut;

                var requestUri = string.Format(RESTfulAPI.APIMap["UpdateRouteStatus"], taskID, routeID, (int)routeStatus);
                var response = httpClient.PostAsync(requestUri, null);
                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    var jsonResult = response.Result.Content.ReadAsStringAsync().Result;

                    var result = JsonConvert.DeserializeAnonymousType(jsonResult, new { isOK = false, msg = "" });

                    _logger.Debug($"RequestUri: {requestUri}, Result: [IsOK={result.isOK}, Msg={result.msg}]");

                    return (result.isOK, result.msg);
                }

                return (false, $"任务路由的线路状态更新失败[StatusCode:{response.Result.StatusCode}]");
            }
        }
    }
}
